package com.now.printer.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;

import com.now.printer.bean.FileBean;
import com.now.printer.bean.ImgFolderBean;
import com.now.printer.db.DocumentsTable;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;

/**
 * @创建人 chaychan
 * @创建时间 2016/7/23  14:34
 * @描述 文件管理者, 可以获取本机的各种文件
 */
public class FileManager {

    private static FileManager mInstance;
    private static Context mContext;
    private static ContentResolver mContentResolver;
    private static Object mLock = new Object();

    public static FileManager getInstance(Context context) {
        if (mInstance == null) {
            synchronized (mLock) {
                if (mInstance == null) {
                    mInstance = new FileManager();
                    mContext = context;
                    mContentResolver = context.getContentResolver();
                }
            }
        }
        return mInstance;
    }

    //                    if (!fileName.endsWith(".doc") || !fileName.endsWith(".docx") ||
//                            !fileName.endsWith(".xls") || !fileName.endsWith(".xlsx")  ||
//                            !fileName.endsWith(".ppt") || !fileName.endsWith(".pptx") ||
//                            !fileName.endsWith(".htm") || !fileName.endsWith(".html") ||
//                            !fileName.endsWith(".txt") || !fileName.endsWith(".png") ||
//                            !fileName.endsWith(".jpg") || !fileName.endsWith(".jpeg")){
//                        continue;
//                    }

    /**
     * 通过文件类型得到相应文件的集合
     **/
    public List<DocumentsTable> getAllFilesList() {
        String[] DOC_PROJECTION = new String[]{MediaStore.Files.FileColumns._ID,
                MediaStore.Files.FileColumns.DATA,
                MediaStore.Files.FileColumns.MIME_TYPE,
                MediaStore.Files.FileColumns.SIZE,
                MediaStore.Files.FileColumns.DATE_ADDED,
                MediaStore.Files.FileColumns.TITLE};

        String selection = MediaStore.Files.FileColumns.MEDIA_TYPE + "!=" + MediaStore.Files.FileColumns.MEDIA_TYPE_AUDIO +
                " AND " + MediaStore.Files.FileColumns.MEDIA_TYPE + "!=" + MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO +
                " AND " + MediaStore.Files.FileColumns.SIZE + "!=" + "0" +

                " AND (" + MediaStore.Files.FileColumns.DATA + " LIKE " + "'%.doc'" +
                " OR " + MediaStore.Files.FileColumns.DATA + " LIKE " + "'%.docx'" +
                " OR " + MediaStore.Files.FileColumns.DATA + " LIKE " + "'%.xls'" +
                " OR " + MediaStore.Files.FileColumns.DATA + " LIKE " + "'%.xlsx'" +
                " OR " + MediaStore.Files.FileColumns.DATA + " LIKE " + "'%.ppt'" +
                " OR " + MediaStore.Files.FileColumns.DATA + " LIKE " + "'%.pptx'" +
                " OR " + MediaStore.Files.FileColumns.DATA + " LIKE " + "'%.htm'" +
                " OR " + MediaStore.Files.FileColumns.DATA + " LIKE " + "'%.html'" +
                " OR " + MediaStore.Files.FileColumns.DATA + " LIKE " + "'%.pdf'" +
                " OR " + MediaStore.Files.FileColumns.DATA + " LIKE " + "'%.txt'" +
                ")";
        Uri uri = MediaStore.Files.getContentUri("external");
        List<DocumentsTable> files = new ArrayList<>();

        Cursor cursor = mContentResolver.query(uri,
                DOC_PROJECTION,
                selection,
                null,
                MediaStore.Files.FileColumns._ID + " DESC");
        while (cursor.moveToNext()) {
            int id = cursor.getInt(cursor.getColumnIndex(MediaStore.Files.FileColumns._ID));
            String path = cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA));
            String fileName = new File(path).getName();
            String size = FileUtils.FormetFileSize(cursor.getLong(cursor.getColumnIndex(MediaStore.Files.FileColumns.SIZE)));
            DocumentsTable parent2 = new DocumentsTable();
            parent2.setId(id);
            parent2.setName(fileName);
            parent2.setPath(path);
            parent2.setSize(size);
            parent2.setLastTime(FileUtils.getModifiedTime(new File(path)));
            parent2.setImageId(FileUtils.getFileIconByPath(path));
            files.add(parent2);
        }

        cursor.close();
        return files;
    }

    //获取所有图片
    public List<DocumentsTable> getAllImagesList() {
        List<DocumentsTable> files = new ArrayList<>();
        // 扫描图片
        Cursor c = null;
        try {
            c = mContentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null,
                    MediaStore.Images.Media.MIME_TYPE + "= ? or " + MediaStore.Images.Media.MIME_TYPE + "= ? or " + MediaStore.Images.Media.MIME_TYPE + "= ?",
                    new String[]{"image/jpeg", "image/png", "image/jpg"}, MediaStore.Images.Media._ID + " DESC"); //MediaStore.Images.Media.DATE_MODIFIED
            List<String> mDirs = new ArrayList<String>();//用于保存已经添加过的文件夹目录
            while (c.moveToNext()) {
                String path = c.getString(c.getColumnIndex(MediaStore.Images.Media.DATA));// 路径
                long id = c.getLong(c.getColumnIndex(MediaStore.Images.Media._ID));// 路径
                String size = FileUtils.FormetFileSize(c.getLong(c.getColumnIndex(MediaStore.Images.Media.SIZE)));

                String fileName = new File(path).getName();

                DocumentsTable parent2 = new DocumentsTable();
                parent2.setId(id);
                parent2.setName(fileName);
                parent2.setPath(path);
                parent2.setSize(size);
                parent2.setLastTime(FileUtils.getModifiedTime(new File(path)));
                parent2.setImageId(FileUtils.getFileIconByPath(path));
                files.add(parent2);

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (c != null) {
                c.close();
            }
        }

        return files;
    }

    /**
     * 得到图片文件夹集合
     */
    public List<ImgFolderBean> getImageFolders() {
        List<ImgFolderBean> folders = new ArrayList<ImgFolderBean>();
        // 扫描图片
        Cursor c = null;
        try {
            c = mContentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null,
                    MediaStore.Images.Media.MIME_TYPE + "= ? or " + MediaStore.Images.Media.MIME_TYPE + "= ?",
                    new String[]{"image/jpeg", "image/png"}, MediaStore.Images.Media.DATE_MODIFIED);
            List<String> mDirs = new ArrayList<String>();//用于保存已经添加过的文件夹目录
            while (c.moveToNext()) {
                String path = c.getString(c.getColumnIndex(MediaStore.Images.Media.DATA));// 路径
                File parentFile = new File(path).getParentFile();
                if (parentFile == null)
                    continue;

                String dir = parentFile.getAbsolutePath();
                if (mDirs.contains(dir))//如果已经添加过
                    continue;

                mDirs.add(dir);//添加到保存目录的集合中
                ImgFolderBean folderBean = new ImgFolderBean();
                folderBean.setDir(dir);
                folderBean.setFistImgPath(path);
                if (parentFile.list() == null)
                    continue;
                int count = parentFile.list(new FilenameFilter() {
                    @Override
                    public boolean accept(File dir, String filename) {
                        if (filename.endsWith(".jpeg") || filename.endsWith(".jpg") || filename.endsWith(".png")) {
                            return true;
                        }
                        return false;
                    }
                }).length;

                folderBean.setCount(count);
                folders.add(folderBean);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (c != null) {
                c.close();
            }
        }

        return folders;
    }

    /**
     * 通过文件类型得到相应文件的集合
     **/
    public List<FileBean> getFilesByTypeSearch(int fileType, String keyStore) {
        List<FileBean> files = new ArrayList<FileBean>();
        // 扫描files文件库
        Cursor c = null;
        try {
            c = mContentResolver.query(MediaStore.Files.getContentUri("external"), new String[]{"_id", "_data", "_size"}, null, null, null);
            int dataindex = c.getColumnIndex(MediaStore.Files.FileColumns.DATA);
            int sizeindex = c.getColumnIndex(MediaStore.Files.FileColumns.SIZE);

            while (c.moveToNext()) {
                String path = c.getString(dataindex);

                if (fileType == FileUtils.TYPE_ALL) {
                    if (FileUtils.getFileTypeAll(path) == fileType) {
                        if (!FileUtils.isExists(path)) {
                            continue;
                        }
                        long size = c.getLong(sizeindex);
                        FileBean fileBean = new FileBean(path, FileUtils.getFileIconByPath(path), new File(path).getName(), FileUtils.FormetFileSize(size), FileUtils.getModifiedTime(new File(path)));
                        if (TextUtils.isEmpty(keyStore)) {
                            files.add(fileBean);
                        } else {
                            if (new File(path).getName().contains("keyStore")) {
                                files.add(fileBean);
                            }
                        }

//                        ToastUtils.toast(fileBean.path);

                    }
                } else {
                    if (FileUtils.getFileType(path) == fileType) {
                        if (!FileUtils.isExists(path)) {
                            continue;
                        }
                        long size = c.getLong(sizeindex);
                        FileBean fileBean = new FileBean(path, FileUtils.getFileIconByPath(path), new File(path).getName(), FileUtils.FormetFileSize(size), FileUtils.getModifiedTime(new File(path)));
                        if (TextUtils.isEmpty(keyStore)) {
                            files.add(fileBean);
                        } else {
                            if (new File(path).getName().contains("keyStore")) {
                                files.add(fileBean);
                            }
                        }

//                        ToastUtils.toast(fileBean.path);

                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (c != null) {
                c.close();
            }
        }
        return files;
    }


    /**
     * 通过图片文件夹的路径获取该目录下的图片
     */
    public List<String> getImgListByDir(String dir) {
        ArrayList<String> imgPaths = new ArrayList<>();
        File directory = new File(dir);
        if (directory == null || !directory.exists()) {
            return imgPaths;
        }
        File[] files = directory.listFiles();
        for (File file : files) {
            String path = file.getAbsolutePath();
            if (FileUtils.isPicFile(path)) {
                imgPaths.add(path);
            }
        }
        return imgPaths;
    }

    public Uri getUri(ContentResolver cr, String path) {
        Uri mediaUri = MediaStore.Files.getContentUri("external");
        Cursor ca = cr.query(mediaUri, new String[]{MediaStore.MediaColumns._ID}, MediaStore.MediaColumns.DATA + "=?", new String[]{path}, null);
        if (ca != null && ca.moveToFirst()) {
            int id = ca.getInt(ca.getColumnIndex(MediaStore.MediaColumns._ID));
            ca.close();
            return MediaStore.Files.getContentUri("external", id);
        }
        if (ca != null) {
            ca.close();
        }
        return null;
    }

}